using System.Security.Cryptography.X509Certificates;
using Duende.IdentityServer.ResponseHandling;
using Duende.IdentityServer.Services;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Service.Auth.Api.Application.IdsValidator;
using Service.Auth.Api.Extensions;
using Service.Auth.Api.Host;
using Service.Core.Behaviors;
using Service.Core.Identity;
using Service.Core.Repository;
using Service.Core.Shared;
using Service.Core.Swagger;
using Service.Framework.AppStartup;

namespace Service.Auth.Api;

/// <summary>
/// 程序启动器 //typeof(CoreSwaggerJwtStartup),
/// </summary>
[ImportStartupModule(typeof(CoreRepositoryStartup),
    typeof(ClientIdentityStartup))]
public class ServiceAuthStartup : AppStartupBase<ServiceAuthStartup>
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="webApplicationBuilder"></param>
    public override void ConfigureServices(WebApplicationBuilder webApplicationBuilder)
    {

        IServiceCollection services = webApplicationBuilder.Services;


        base.ConfigureServices(webApplicationBuilder);

        webApplicationBuilder.AddSwaggerService();


        //SignalR
        services.AddSignalR();

        #region 取消默认验证Api 接收参数模型 的 验证特性 如有 [ApiController]

        services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; });

        #endregion


        // Configure mediatR
        services.AddMediatR(cfg => { cfg.RegisterServicesFromAssemblyContaining(typeof(Program)); });
        services.AddScoped(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>)); //注入日志管道捕获请求。
        services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); //注入验证管道捕获请求。

        services.AddTransient<IRefreshTokenService, CustomRefreshTokenService>();

        services.AddTransient<ITokenCreationService, CustomTokenCreationService>();

        var x509Certificate2 = X509CertificateLoader.LoadPkcs12FromFile(Path.Combine(webApplicationBuilder.Environment.ContentRootPath, "keys", "certificate.pfx"), "Pass1234!");

        services.AddIdentityServer(option =>
        {
        })
            .AddDeveloperSigningCredential()
            .AddSigningCredential(x509Certificate2)
            .AddExtensionGrantValidator<RoleResourceOwnerPhoneValidator>()
            .AddResourceOwnerValidator<RoleResourceOwnerPasswordValidator>()
            .AddSqlSuagerStore();
        services.AddHostedService<AuthHostService>();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="webApplication"></param>
    public override void Configure(WebApplication webApplication)
    {
        webApplication.UseIdentityServer();
        webApplication.AddSwaggerConfigure();
        base.Configure(webApplication);
    }

    /// <summary>
    /// 程序启动
    /// </summary>
    /// <param name="webApplication"></param>
    public override void ApplicationStarted(WebApplication webApplication)
    {
    }
}